package com.zhongxi.guoyuan.view.user.gift;

import android.app.AlertDialog;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.weigan.loopview.LoopView;
import com.weigan.loopview.OnItemSelectedListener;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.EventBusMessage;
import com.zhongxi.guoyuan.entity.code.CodeResult;
import com.zhongxi.guoyuan.entity.shopcart.City;
import com.zhongxi.guoyuan.entity.shopcart.CityData;
import com.zhongxi.guoyuan.entity.shopcart.Prefecture;
import com.zhongxi.guoyuan.entity.shopcart.PrefectureData;
import com.zhongxi.guoyuan.entity.shopcart.Province;
import com.zhongxi.guoyuan.entity.shopcart.ProvinceData;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.RegularTool;
import com.zhongxi.guoyuan.utils.ToastUtil;
import com.zhongxi.guoyuan.utils.UiUtils;
import com.zhongxi.guoyuan.widget.screenadaptaion.CustomLinearlayout;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/4/23.
 */

public class DialogGiftActivity extends BaseActivity {
    @Bind(R.id.iv_dimess)
    ImageView mIvDimess;
    @Bind(R.id.et_name)
    EditText mEtName;
    @Bind(R.id.et_phone)
    EditText mEtPhone;
    @Bind(R.id.tv_verifyCode)
    TextView mTvVerifyCode;
    @Bind(R.id.et_code)
    EditText mEtCode;
    @Bind(R.id.tv_province)
    TextView mTvProvince;
    @Bind(R.id.tv_city)
    TextView mTvCity;
    @Bind(R.id.tv_country)
    TextView mTvCountry;
    @Bind(R.id.et_address)
    EditText mEtAddress;
    @Bind(R.id.tv_submit)
    TextView mTvSubmit;
    @Bind(R.id.ll_addressInfo)
    CustomLinearlayout mLlAddressInfo;
    @Bind(R.id.ll_detail_address)
    CustomLinearlayout mLlDetailAddress;
    private String type;
    private Map<String, String> map = new HashMap<>();
    private String mCert;
    private int addressPos = 0;
    private int cityPos = 0;
    private int prefPos = 0;
    private List<ProvinceData> provinceData;
    private List<CityData> cityData;
    private List<PrefectureData> prefectureData;
    private int mPostFlay;


    /*定义一个倒计时的内部类*/
    class TimeCount extends CountDownTimer {

        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);//参数依次为总时长，和计时的时间间隔
        }

        @Override
        public void onTick(long millisUntilFinished) {//计时过程显示
            mTvVerifyCode.setClickable(false);
            mTvVerifyCode.setText(millisUntilFinished / 1000 + "s");
        }

        @Override
        public void onFinish() {//计时完毕时触发
            mTvVerifyCode.setText("验证码");
            mTvVerifyCode.setClickable(true);
        }

    }

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.dialog_gift_edit);
        ButterKnife.bind(this);
        if (getIntent() != null) {
            mCert = getIntent().getStringExtra("cert");
            mPostFlay = getIntent().getIntExtra("postFlay", 0);  //  1 邮寄  2  自提
        }

        if (mPostFlay == 1) {
            mLlAddressInfo.setVisibility(View.VISIBLE);
            mLlDetailAddress.setVisibility(View.VISIBLE);
        } else {
            mLlAddressInfo.setVisibility(View.GONE);
            mLlDetailAddress.setVisibility(View.GONE);
        }
    }


    @OnClick({R.id.iv_dimess, R.id.tv_verifyCode, R.id.tv_province, R.id.tv_city, R.id.tv_country, R.id.tv_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_dimess:
                finish();
                break;
            case R.id.tv_verifyCode:
                getSendCode();
                break;
            case R.id.tv_province:
                getProvince();
                break;
            case R.id.tv_city:
                if (provinceData != null && provinceData.size() > 0) {
                    getCity();
                } else {
                    showShortToast("请先选择 省份");
                }
                break;
            case R.id.tv_country:
                if (cityData != null && cityData.size() > 0) {
                    getPrefecture();
                } else {
                    showShortToast("请先选择城市");
                }
                break;
            case R.id.tv_submit:
                if (1 == mPostFlay) {
                    String mName = mEtName.getText().toString().trim();
                    String mPhone = mEtPhone.getText().toString().trim();
                    String mCode = mEtCode.getText().toString().trim();
                    String mProvince = mTvProvince.getText().toString().trim();
                    String mCity = mTvCity.getText().toString().trim();
                    String mCountry = mTvCountry.getText().toString().trim();
                    String mAddress = mEtAddress.getText().toString().trim();
                    if (TextUtils.isEmpty(mName)) {
                        ToastUtil.show("请输入您的名字");
                    } else if (TextUtils.isEmpty(mPhone)) {
                        ToastUtil.show("请输入您的手机号");
                    } else if (TextUtils.isEmpty(mCode)) {
                        ToastUtil.show("请输入您的验证码");
                    } else if (TextUtils.isEmpty(mProvince)) {
                        ToastUtil.show("请输入您所在省份");
                    } else if (TextUtils.isEmpty(mCity)) {
                        ToastUtil.show("请输入您所在城市");
                    } else if (TextUtils.isEmpty(mCountry)) {
                        ToastUtil.show("请输入您所在县区");
                    } else if (TextUtils.isEmpty(mAddress)) {
                        ToastUtil.show("请输入您的详细地址");
                    } else {
                        finish();
                        EventBus.getDefault().post(new EventBusMessage(mName, mPhone, mCode, mProvince, mCity, mCountry, mAddress));
                    }
                } else {
                    String mName = mEtName.getText().toString().trim();
                    String mPhone = mEtPhone.getText().toString().trim();
                    String mCode = mEtCode.getText().toString().trim();
                    if (TextUtils.isEmpty(mName)) {
                        ToastUtil.show("请输入您的名字");
                    } else if (TextUtils.isEmpty(mPhone)) {
                        ToastUtil.show("请输入您的手机号");
                    } else if (TextUtils.isEmpty(mCode)) {
                        ToastUtil.show("请输入您的验证码");
                    } else {
                        finish();
                        EventBus.getDefault().post(new EventBusMessage(mName, mPhone, mCode));
                    }
                }
                break;
        }
    }

    private void getSendCode() {
        String phone = mEtPhone.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            ToastUtil.show("手机号为空");
        } else if (!RegularTool.isPhoneNumberValid(phone)) {
            showShortToast("请输入正确的手机号");
        } else {
            type = "sendcode";
            TimeCount time = new TimeCount(60000, 1000);
            time.start();
            map.clear();
            map.put("phoneno", phone);
            map.put("cert", mCert);
            getServer(Url.ACTIVITY_SENDCODE, map, "", false, null, "post");
        }
    }

    /**
     * 获取省份列表
     */
    private void getProvince() {
        type = "province";
        getServer(Url.REWARD_PROVINCE_LIST, null, "", false, null, "get");
    }

    /**
     * 获取城市列表
     */
    private void getCity() {
        type = "city";
        String str = "";
        str = "&pid=" + provinceData.get(addressPos).getP_id();
        getServer(Url.REWARD_CITY_LIST, null, str, false, null, "get");
    }

    /**
     * 获取区县列表
     */
    private void getPrefecture() {
        type = "prefecture";
        String str = "";
        str = "&pid=" + provinceData.get(addressPos).getP_id() + "&cid=" + cityData.get(cityPos).getC_id();
        getServer(Url.REWARD_PREFECTURE_LIST, null, str, false, null, "get");
    }


    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson mGson = new Gson();
        if ("sendcode".equals(type)) {
            CodeResult result = mGson.fromJson(response, CodeResult.class);
            MyApplication.getInstance().setSpValue(result.getSafeobj());
        } else if ("province".equals(type)) {
            Province province = mGson.fromJson(response, Province.class);
            MyApplication.getInstance().setSpValue(province.getSafeobj());
            List<String> provinceList = new ArrayList<>();
            if (province.getData() != null && province.getData().size() > 0) {
                provinceData = province.getData();
                for (int i = 0; i < provinceData.size(); i++) {
                    provinceList.add(provinceData.get(i).getProvince());
                }
                showProvinceDialog(provinceList, 1, 0);
            } else {
                showShortToast("赞无数据");
            }
        } else if ("city".equals(type)) {
            City city = mGson.fromJson(response, City.class);
            if (null != city.getSafeobj() && !"".equals(city.getSafeobj())) {
                MyApplication.getInstance().setSpValue(city.getSafeobj());
            }
            List<String> cityList = new ArrayList<>();
            if (city.getData() != null && city.getData().size() > 0) {
                cityData = city.getData();
                for (int i = 0; i < cityData.size(); i++) {
                    cityList.add(cityData.get(i).getCity());
                }
                showProvinceDialog(cityList, 2, 0);
            } else {
                showShortToast("赞无数据");
            }
        } else if ("prefecture".equals(type)) {
            Prefecture prefecture = mGson.fromJson(response, Prefecture.class);
            if (null != prefecture.getSafeobj() && !"".equals(prefecture.getSafeobj())) {
                MyApplication.getInstance().setSpValue(prefecture.getSafeobj());
            }
            List<String> prefectureList = new ArrayList<>();
            if (prefecture.getData() != null && prefecture.getData().size() > 0) {
                prefectureData = prefecture.getData();
                for (int i = 0; i < prefectureData.size(); i++) {
                    prefectureList.add(prefectureData.get(i).getPrefecture());
                }
                showProvinceDialog(prefectureList, 3, 0);
            } else {
                showShortToast("赞无数据");
            }
        }
    }

    private void showProvinceDialog(final List<String> list, final int flag, int pos) {
        final AlertDialog adb = new AlertDialog.Builder(context).create();
        View view = UiUtils.inflate(R.layout.dialog_view);
        TextView tvNo = (TextView) view.findViewById(R.id.tv_no);
        TextView tvYes = (TextView) view.findViewById(R.id.tv_yes);
        LoopView loopView = (LoopView) view.findViewById(R.id.loopView);
        loopView.setItems(list);
        loopView.setListener(new OnItemSelectedListener() {
            @Override
            public void onItemSelected(int index) {
                switch (flag) {
                    case 1:
                        addressPos = index;
                        break;
                    case 2:
                        cityPos = index;
                        break;
                    case 3:
                        prefPos = index;
                        break;
                }
            }
        });
        loopView.setNotLoop();  //停止无线轮播
        loopView.setInitPosition(pos);
        tvNo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                adb.dismiss();
                switch (flag) {
                    case 1:
                        mTvProvince.setText(list.get(0));
                        break;
                    case 2:
                        mTvCity.setText(list.get(0));
                        break;
                    case 3:
                        mTvCountry.setText(list.get(0));
                        break;
                }
            }
        });

        tvYes.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                adb.dismiss();
                switch (flag) {
                    case 1:
                        mTvProvince.setText(list.get(addressPos));
                        break;
                    case 2:
                        mTvCity.setText(list.get(cityPos));
                        break;
                    case 3:
                        mTvCountry.setText(list.get(prefPos));
                        break;
                }
            }
        });
        adb.setView(view);
        adb.show();
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson mGson = new Gson();
        BaseResponse mBaseResponse = mGson.fromJson(response, BaseResponse.class);
        MyApplication.getInstance().setSpValue(mBaseResponse.getSafeobj());
    }
}
